package com.nexgo.payment.trans.download;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.nexgo.common.ByteUtils;
import com.nexgo.common.TlvUtils;
import com.nexgo.data.entity.RecvData;
import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.oaf.apiv3.emv.EmvHandler;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.trans.AbsOnlinePresenter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by xiaox on 2017/8/11.
 */
public class AidParamPresenter extends AbsOnlinePresenter implements DownloadTransContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(AidParamPresenter.class.getSimpleName());

    private DownloadTransContract.View mView;
    private List<String> mAidList;
    private int mTotal = 0;

    AidParamPresenter(@NonNull DownloadTransContract.View view, @NonNull DataSource repository) {
        super(view, repository);
        mView = checkNotNull(view);
        mAidList = new ArrayList<>();
    }

    @Override
    protected TransData getTransData() {
        TransData transData = new TransData();
//        transData.setTransType(TransType.AID_NOTIFY);
        transData.setTransType(TransType.AID_DOWN);
        transData.setTemporary("0000");
        return transData;
    }

    @Override
    protected void onFirstAction() {
        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.aid_notify)));
    }

    @Override
    protected void onTransSuccess(RecvData recvData) {
        if (TransType.AID_NOTIFY.equals(mTransData.getTransType())) {
            //查询包
            if (TextUtils.isEmpty(recvData.getField62())) {
                postMainThread(() -> mView.showTransFailed());
                return;
            }
            byte[] value = ByteUtils.hexString2ByteArray(recvData.getField62());
            byte mode = value[0];
            if (mode == '0') {
                mTransData.setTransType(TransType.AID_END);
                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.aid_end)));
            } else if (mode == '1' || mode == '2' || mode == '3') {
                //1表示只有一条
                //2表示要继续发起通知查询
                //3表示最后一条
                //缓存起aid索引数据，用于发送aid下载包用
                String aid = ByteUtils.byteArray2HexString(Arrays.copyOfRange(value, 1, value.length));
                List<String> aidList = TlvUtils.decodingTLV(aid, "9f06");
                if (aidList == null || aidList.size() == 0) {
                    postMainThread(() -> mView.showTransFailed());
                    return;
                }
                mTransData.setCounter(mTransData.getCounter() + aidList.size());
                mTransData.setTemporary(mTransData.getTemporary() + aid);
                if (mode != '2') {
                    //改交易类型，发起aid下载包
                    mTotal = mTransData.getCounter();
                    mTransData.setTransType(TransType.AID_DOWN);
                    postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.aid_down)));
                } else {
                    postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.aid_notify)));
                }
            } else {
                postMainThread(() -> mView.showTransFailed());
            }
        } else if (TransType.AID_DOWN.equals(mTransData.getTransType())) {
            //下载包
            byte[] value = ByteUtils.hexString2ByteArray(recvData.getField60());
            if (value == null || value.length <= 1) {
                postMainThread(() -> mView.showTransFailed());
                return;
            }
//           wzp add  交行特殊处理下发AID位1000 影响非接交易
            String str = recvData.getField60();

            int i = str.indexOf("DF20");
            if(i > 0){
                mLog.debug("  i {} before change{}", i , str);
                StringBuilder sb = new StringBuilder(str);
                sb.replace(i + 6, i+ 6 + 12, "000999999999");
                final String aidString = sb.toString();
                mLog.debug("after change {}", aidString);
                mAidList.add(aidString);
            }
            else
                mAidList.add(str);


            int over = Integer.parseInt(recvData.getfield28());
            if (over == 0) {
                //计数器为0，开始下灌aid列表
                EmvHandler sdkEmvHandler = ApiDeviceEngine.getDefaultEmvHandler();
                sdkEmvHandler.delAllAid();
                for (String aid : mAidList) {
                    mLog.debug("mAidList change {}", aid);
                }
                int ret = sdkEmvHandler.setAidParaList(mAidList);
                if (ret == SdkResult.Success) {
                    //结束包
                    postMainThread(() -> mView.showTransSuccess());
//                    mTransData.setTransType(TransType.AID_END);
//                    postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.aid_end)));
                } else {
                    postMainThread(() -> mView.showTransFailed());
                }
            } else {
                //继续发起aid下载包
                //wzp add 获取AID 下载偏移
                mTransData.setTemporary(recvData.getTrack2());
                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.aid_down)));
//                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.aid_down, String.valueOf(mTotal - mTransData.getCounter() + 1), String.valueOf(mTotal))));
            }
        } else {
            //结束包
            postMainThread(() -> mView.showTransSuccess());
        }
    }
}
